package com.cx.jvm;

import com.alibaba.druid.sql.parser.Lexer;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;

/**
 * @Author: robert.song
 * @Date: Created in 2021/10/8
 */
public class WeakReferenceDemo {
    public static void main(String[] args) throws InterruptedException {
        Lexer.SavePoint savePoint = new Lexer.SavePoint(); // 创建一个强引用
        ReferenceQueue<Lexer.SavePoint> savepointQ = new ReferenceQueue<Lexer.SavePoint>();//引用队列
        WeakReference<Lexer.SavePoint> savePointWRefernce = new WeakReference<Lexer.SavePoint>(savePoint, savepointQ);
        System.out.println("SavePoint 被作为一个弱引用来创建" + savePointWRefernce);
        Runtime.getRuntime().gc();
        System.out.println("在引用队列中存在引用型对象吗 ? " + (savepointQ.poll() != null));
        savePoint = null; // 唯一的强引用被删除掉，在堆中的对象现在只具有弱可达性
        System.out.println("现在调用GC");
        Runtime.getRuntime().gc(); // 对象会在这里被回收掉，finalize方法会被调用
        System.out.println("弱引用型对象还引用堆中的对象吗?" + (savePointWRefernce.get() != null));
        System.out.println("弱引用型对象被添加到引用队列中了吗?" + (savePointWRefernce.isEnqueued()));
        System.out.println("在引用队列中有任何弱引用吗? " + (savepointQ.remove() != null));
        System.out.println("remove()方法执行后，弱引用型对象被添加到引用队列中了吗?" + (savePointWRefernce.isEnqueued()));
    }
}
